import { defineStore } from "pinia"
import { ref,watch } from "vue"


const STORAGE_KEY = 'user_login_info'


export const useUserStore = defineStore('user', () => {
    const isLoggedIn = ref(false)
    const username = ref('')
    const role = ref('') //'student' 或 'teacher'

    //从Local Storage 中恢复用户状态
    const loadUser = () => {
        const sotredData = localStorage.getItem(STORAGE_KEY)
        if (sotredData){
            const userData = JSON.parse(sotredData)
            isLoggedIn.value = userData.isLoggedIn
            username.value = userData.username
            role.value = userData.role
        }
    }

    const login = (user) => {
        isLoggedIn.value = true
        username.value = user.username
        role.value = user.role

        localStorage.setItem(
            STORAGE_KEY,
            JSON.stringify({isLoggedIn: true, username: user.username, role: user.role})
        )
    };

    const logout = () => {
        isLoggedIn.value = false;
        username.value = '';
        role.value = '';
        localStorage.removeItem(STORAGE_KEY)
    };

    watch(
        [isLoggedIn, username, role],
        () => {
            if(isLoggedIn.value){
                localStorage.setItem(
                    STORAGE_KEY,
                    JSON.stringify({ isLoggedIn: isLoggedIn.value, username: username.value, role: role.value })
                )
            }
        },
        { deep: true }
    )

    loadUser(
        
    )
    return {isLoggedIn,username,role,login,logout};
});